package config

import (
	"fmt"
	"github.com/spf13/viper"
	"strings"
)

type Config struct {
	DatabaseDSN   string
	RedisAddr     string
	RedisPassword string
	RedisDB       int
}

func LoadConfig() *Config {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./config")
	viper.AutomaticEnv()

	// 环境变量格式为DB_USER/REDIS_PASSWORD
	// viper大小写不敏感，但是需要将下划线转为'.'，使viper可以访问到yaml
	replacer := strings.NewReplacer(".", "_")
	viper.SetEnvKeyReplacer(replacer)

	if err := viper.ReadInConfig(); err != nil {
		panic(fmt.Errorf("配置文件读取失败: %w", err))
	}

	return &Config{
		DatabaseDSN: fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True",
			viper.GetString("db.user"),
			viper.GetString("db.password"),
			viper.GetString("db.host"),
			viper.GetString("db.port"),
			viper.GetString("db.name"),
		),
		RedisAddr:     viper.GetString("redis.address"),
		RedisPassword: viper.GetString("redis.password"),
		RedisDB:       viper.GetInt("redis.database"),
	}
}
